<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import type { BoardIndex, BoardState, ChessPiece, DifficultyLevel, GameStatus } from './types'
import { useAI } from './hooks/useAI'

const ai = useAI()
const router = useRouter()

const board = ref<BoardState>(Array(9).fill(null))

const playerPiece = ref<ChessPiece>('X')
const aiPiece = computed(() => (playerPiece.value === 'X' ? 'O' : 'X'))

const difficulty = ref<DifficultyLevel>('medium')

const gameStatus = ref<GameStatus>('idle')

const wins = ref(0)
const losses = ref(0)
const draws = ref(0)

const winningLine = ref<BoardIndex[]>([])

const isPlaying = computed(() => gameStatus.value === 'playing')

const winRate = computed(() => {
  const total = wins.value + losses.value + draws.value
  if (total === 0)
    return 0
  return Math.round((wins.value / total) * 100)
})

const gameStatusText = computed(() => {
  switch (gameStatus.value) {
    case 'idle': return '未开始'
    case 'playing': return '游戏中'
    case 'win': return '你赢了！'
    case 'lose': return '你输了'
    case 'draw': return '平局'
    default: return ''
  }
})

function finishGame(status: GameStatus, line: BoardIndex[] = []) {
  gameStatus.value = status
  winningLine.value = line

  let msg = ''
  if (status === 'win') {
    wins.value++
    msg = '你赢了！恭喜！'
  }
  else if (status === 'lose') {
    losses.value++
    msg = '你输了，再接再厉！'
  }
  else if (status === 'draw') {
    draws.value++
    msg = '平局！'
  }

  ElMessageBox.alert(msg, '游戏结束', {
    confirmButtonText: '重新开始',
    cancelButtonText: '退出游戏',
    showCancelButton: true,
    closeOnClickModal: false,
    closeOnPressEscape: false,
  }).then(() => {
    startGame()
  }).catch(() => {
    gameStatus.value = 'idle'
    board.value = Array(9).fill(null)
    winningLine.value = []
  })
}

function isPlayerTurn(): boolean {
  const totalMoves = board.value.filter(c => c !== null).length
  const currentTurnPiece: ChessPiece = totalMoves % 2 === 0 ? 'X' : 'O'
  return currentTurnPiece === playerPiece.value
}

function playerMove(index: number) {
  if (!isPlaying.value) {
    return ElMessage.warning('请先点击开始游戏')
  }
  if (!isPlayerTurn())
    return
  if (board.value[index] !== null)
    return

  board.value[index] = playerPiece.value

  const winnerLine = checkWinnerLine(board.value)
  if (winnerLine) {
    finishGame('win', winnerLine)
    return
  }

  if (!board.value.includes(null)) {
    finishGame('draw')
    return
  }
  // 300ms延时后操作
  setTimeout(aiMove, 300)
}

function aiMove() {
  if (gameStatus.value !== 'playing')
    return

  const move = ai.getMove(difficulty.value, board.value, aiPiece.value, playerPiece.value)
  if (move === null) {
    finishGame('draw')
    return
  }
  board.value[move] = aiPiece.value

  const winnerLine = checkWinnerLine(board.value)
  if (winnerLine) {
    finishGame('lose', winnerLine)
    return
  }

  if (!board.value.includes(null)) {
    finishGame('draw')
  }
}

function checkWinnerLine(boardState: BoardState): BoardIndex[] | null {
  const winPatterns: BoardIndex[][] = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ]
  for (const pattern of winPatterns) {
    const [a, b, c] = pattern
    if (
      boardState[a]
      && boardState[a] === boardState[b]
      && boardState[a] === boardState[c]
    ) {
      return pattern
    }
  }
  return null
}

function startGame() {
  board.value = Array(9).fill(null)
  winningLine.value = []
  gameStatus.value = 'playing'

  // ✨ 新增：提示谁先手
  ElMessage.success(playerPiece.value === 'X' ? '你是 X，先手走棋' : '你是 O，AI 先手走棋')

  if (playerPiece.value === 'O') {
    // AI 先手 300ms延时后操作
    setTimeout(() => {
      aiMove()
    }, 300)
  }
}

function resetStats() {
  wins.value = 0
  losses.value = 0
  draws.value = 0
}

function goHome() {
  router.push('/')
}
</script>

<template>
  <div class="tic-tac-toe-container">
    <h2>井字棋游戏</h2>

    <div class="settings">
      <div class="top">
        <el-radio-group v-model="playerPiece" :disabled="isPlaying">
          <el-radio label="X">
            X
          </el-radio>
          <el-radio label="O">
            O
          </el-radio>
        </el-radio-group>

        <el-select v-model="difficulty" placeholder="选择难度" style="width: 140px;" :disabled="isPlaying">
          <el-option label="简单" value="easy" />
          <el-option label="中等" value="medium" />
          <el-option label="困难" value="hard" />
        </el-select>
      </div>
      <div class="button">
        <el-button :type="isPlaying ? 'warning' : 'success'" @click="startGame">
          {{ isPlaying ? '重新开始' : '开始游戏' }}
        </el-button>
        <el-button @click="goHome">
          返回首页
        </el-button>
      </div>
    </div>

    <div class="status-bar">
      <div>当前状态: <strong>{{ gameStatusText }}</strong></div>
      <div>玩家（{{ playerPiece }}）胜率: {{ winRate }}%</div>
      <el-button type="warning" :disabled="isPlaying" @click="resetStats">
        重置胜率
      </el-button>
    </div>

    <div class="board">
      <div
        v-for="(cell, index) in board"
        :key="index"
        class="cell"
        :class="{
          'cell-x': cell === 'X',
          'cell-o': cell === 'O',
          'cell-highlight': winningLine.includes(index),
        }"
        @click="playerMove(index)"
      >
        <span v-if="cell === 'X'" class="piece-x">X</span>
        <span v-if="cell === 'O'" class="piece-o">O</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.tic-tac-toe-container {
  max-width: 420px;
  margin: 20px auto;
  text-align: center;
  user-select: none;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.settings {
  margin-bottom: 12px;
  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    margin: 12px 0;
  }
}

.status-bar {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-around;
  font-size: 14px;
  color: #555;
  align-items: center;
  flex-wrap: wrap;
}

.board {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  user-select: none;
  justify-content: center;
  max-width: 360px;
  margin: 0 auto;
}

.cell {
  position: relative;
  width: 100px;
  height: 100px;
  background: #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 64px;
  font-weight: 900;
  color: #999;
  user-select: none;
  overflow: hidden;
}

.cell:hover {
  background-color: #e0e0e0;
}

.cell-x {
  color: #d32f2f;
}

.cell-o {
  color: #1976d2;
}

.cell-highlight {
  background-color: #ffe082;
  box-shadow: 0 0 12px 4px #ffca28;
  cursor: default;
}

.piece-x,
.piece-o {
  position: relative;
  display: block;
  animation: fadeInScale 0.3s ease forwards;
}

@keyframes fadeInScale {
  0% {
    opacity: 0;
    transform: scale(0.5);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@media (max-width: 480px) {
  .cell {
    width: 80px;
    height: 80px;
    font-size: 48px;
  }
  .tic-tac-toe-container {
    max-width: 320px;
  }
}
</style>
